package com.kxf.pushkeepalive;

import android.Manifest;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.kxf.pushkeepalive.activity.AccbDescActivity;
import com.kxf.pushkeepalive.process.PushRemoteService;
import com.kxf.pushkeepalive.service.MyForeService;
import com.kxf.pushkeepalive.service.MyJobService;
import com.kxf.pushkeepalive.service.PushAccessibilityService;
import com.kxf.pushkeepalive.utils.ProcessUtils;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.concurrent.TimeUnit;

import rx.functions.Action1;

public class MainActivity extends AppCompatActivity {

    private boolean isActityAlive = false;
    private boolean isCheckedAbService = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //分别申请多个权限
        RxPermissions.getInstance(MainActivity.this)
                //分别申请多个权限时，使用requestEach
                .requestEach(Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE)
                .subscribe(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Log.d("MainActivity", "permission=" + permission);
                    }
                });

        isActityAlive = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isActityAlive) {
                    boolean b = ProcessUtils.isServiceWorked(MainActivity.this, PushRemoteService.class.getName());
                    Log.d("MainActivity", "PushRemoteService=" + b);
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        getToken();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, MyForeService.class));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            doJobService();
        }
    }

    public void openService(View view) {
        startService(new Intent(this, PushRemoteService.class));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isCheckedAbService && !ProcessUtils.isServiceWorked(this, PushAccessibilityService.class.getName())){
            isCheckedAbService = true;
            startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
            startActivity(new Intent(this, AccbDescActivity.class));
        }else if (!ProcessUtils.isIgnoringBatteryOptimizations(this)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestIgnoreBatteryOptimizations();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isActityAlive = false;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getToken() {
        new Thread() {
            @Override
            public void run() {
                try {
                    // read from agconnect-services.json
                    String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
                    String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, "HCM");
                    Log.i("MainActivity", "get token:" + token);
                    if(!TextUtils.isEmpty(token)) {
                        sendRegTokenToServer(token);
                    }
                } catch (ApiException e) {
                    Log.e("MainActivity", "get token failed, " + e);
                }
            }
        }.start();
    }
    private void sendRegTokenToServer(String token) {
        Log.i("MainActivity", "sending token to server. token:" + token);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void doJobService() {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(this, MyJobService.class));  //指定哪个JobService执行操作
        builder.setMinimumLatency(TimeUnit.MILLISECONDS.toMillis(10)); //执行的最小延迟时间
        builder.setOverrideDeadline(TimeUnit.MILLISECONDS.toMillis(15));  //执行的最长延时时间
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NOT_ROAMING);  //非漫游网络状态
        builder.setBackoffCriteria(TimeUnit.MINUTES.toMillis(10), JobInfo.BACKOFF_POLICY_LINEAR);  //线性重试方案
        builder.setRequiresCharging(false); // 未充电状态
        jobScheduler.schedule(builder.build());
    }

    public void openBootSetting(View view) {
        try {
            startActivityForResult(ProcessUtils.getAutostartSettingIntent(this), 2009);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d("MainActivity", "requestCode=" + requestCode);
        super.onActivityResult(requestCode, resultCode, data);
    }
}
